package com.ouroboroswiki.core.content;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.ouroboroswiki.core.ContentRepository;
import com.ouroboroswiki.core.ContentRepositoryFactory;

public class ToBasePathContentRepositoryProxyFactory implements
		ContentRepositoryFactory {
	
	private ContentRepositoryFactory proxied;
	private Map<String, ToBasePathsContentRepositoryProxy> populated;
	
	public ToBasePathContentRepositoryProxyFactory( ContentRepositoryFactory proxied ) {
		this.proxied = proxied;
		this.populated = new HashMap<String, ToBasePathsContentRepositoryProxy>();
	}
	
	public Collection<ContentRepository> getRepositories() {
		Collection<ContentRepository> repositories = proxied.getRepositories();
		ArrayList<ContentRepository> result = new ArrayList<ContentRepository>( repositories.size() );
		for( ContentRepository repository : repositories ) {
			ToBasePathsContentRepositoryProxy proxy = this.populated.get(repository.getName());
			if( proxy == null ) {
				proxy = toProxy( repository.getName(), repository );
			}
			result.add( proxy );
		}
		return result;
	}
	
	@Override
	public ContentRepository getRepository(String name) {
		ToBasePathsContentRepositoryProxy result;
		result = populated.get(name);
		if( result == null ) {
			ContentRepository repository = proxied.getRepository(name);
			if( repository != null ) {
				result = toProxy( name, repository );
			} else {
				result = null;
			}
		}
		return result;
	}
	
	public ToBasePathsContentRepositoryProxy toProxy( String name, ContentRepository repository ) {
		ToBasePathsContentRepositoryProxy result = new ToBasePathsContentRepositoryProxy();
		result.setProxied(repository);
		this.populated.put(name, result);
		return result;
	}

}
